package com.example.pomelo_home.controller;


import com.example.pomelo_home.entity.User;
import com.example.pomelo_home.service.IUserService;
import com.example.pomelo_home.service.JwtTokenService;
import com.example.pomelo_home.service.WeChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("login")
public class LoginController {
    @Autowired
    private IUserService userService;

    @Autowired
    private JwtTokenService jwtTokenService;

    @Autowired
    private WeChatService weChatService;

    @PostMapping("/loginByCode/{code}")
    public Map<String, Object> login(@PathVariable String code) {
        //System.out.println(code);
        String openid = weChatService.getOpenid(code);

        // 检查用户是否已存在
        User user = userService.findByOpenid(openid).orElseGet(() -> {
            User newUser = new User();
            newUser.setOpenid(openid);
            return userService.save(newUser);
        });

        // 生成JWT令牌
        String token = jwtTokenService.generateToken(openid);

        // 返回响应
        Map<String, Object> response = new HashMap<>();
        response.put("user", user);
        response.put("token", token);
        return response;
    }
}

